//
//  DevChartModel.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/24.
//

#import "DevChartModel.h"
#import "ChartYAxisModel.h"
#import "DeviceChartFieldModel.h"

@implementation DevChartModel

- (NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

- (NSArray<ChartYAxisModel *> *)yAxisArray{
    if (!_yAxisArray) {
        _yAxisArray = [NSArray array];
    }
    return _yAxisArray;
}

-(instancetype)init
{
    if (self = [super init]) {
        self.maxSelectCount = 6;
    }
    return self;
}

//获取质数
- (void)primeNumber{
    NSMutableArray *primeNumberArray = [NSMutableArray array];
    for(int i=2; i<=100; i++) {
        NSInteger n = 0;
        for(int j=1;j<=i;j++) {
            if(i%j == 0) {
                n = n + 1;
            }
        }

        if(n == 2) {
             [primeNumberArray addObject:@(i)];
        }
    }
    NSLog(@"primeNumber = %@",primeNumberArray);
}


//设置参数数据--同步设置默认选中项
- (void)setParams:(NSArray *)params{
    _params = params;
    [self.selectArray removeAllObjects];
    [_params enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartFieldModel *model = [DeviceChartFieldModel yy_modelWithDictionary:[obj yy_modelToJSONObject]];
        //最大曲线个数
        if (idx < self.maxSelectCount) {
            model.isShowLine = YES;
            [self.selectArray addObject:model];
        }
    }];
}

//设置时间
- (void)setCurTime:(NSString *)curTime{
    _curTime = curTime;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_curTime integerValue]];
    NSMutableArray *array = [NSMutableArray array];
    if (self.timeType == TimeType_Day) {
        if ([date isToday]) {
            for (NSInteger i = 0; i<=date.hour; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld:00",i]];
            }
        }else{
            for (NSInteger i = 0; i<=24; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld:00",i]];
            }
        }
    }else if (self.timeType == TimeType_Month) {
        if ([[NSDate date] monthsLaterThan:date]) {
            for (NSInteger i = 1; i<=[date daysInMonth]; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld",i]];
            }
        }else{
            for (NSInteger i = 1; i<=date.day; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld",i]];
            }
        }
    }else if (self.timeType == TimeType_Year){
        if ([[NSDate date] yearsLaterThan:date]) {
            for (NSInteger i = 1; i<=12; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld",i]];
            }
        }else{
            for (NSInteger i = 1; i<=date.month; i++) {
                [array addObject:[NSString stringWithFormat:@"%ld",i]];
            }
        }
    }
    
//    self.xTitlesArray = array;
    //NSLog(@"self.xTitlesArray === %@",[self.xTitlesArray debugDescription]);
}

- (void)setMYDataArray:(NSArray *)mYDataArray{
    _mYDataArray = mYDataArray;
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *dic  in _mYDataArray) {
        NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
        NSDictionary *first_dic = dic[@"first"];
        NSDictionary *last_dic = dic[@"last"];
        [dicc setObject:last_dic[@"time"] forKey:@"time"];
        for (DeviceChartFieldModel *fielModel in self.selectArray) {
            float last_num = [last_dic[fielModel.keyName] floatValue];
            float first_num = [first_dic[fielModel.keyName] floatValue];
            
            float resultValue = last_num-first_num;
            
            [dicc setObject:[NSString stringWithFormat:@"%.1f",resultValue] forKey:fielModel.keyName];
        }
        [array addObject:dicc];
    }
    
    NSLog(@"array ------ %@",[array debugDescription]);
    self.allDataArray = array;
}


//数据重新组合
- (void)setAllDataArray:(NSArray *)allDataArray{
    _allDataArray = allDataArray;
    if(allDataArray.count == 0){
        NSMutableArray *keys = [NSMutableArray array];
        for (DeviceChartFieldModel *fileld in self.selectArray) {
            //将key值提取出来
            [keys addObject:fileld.keyName];
        }
        
        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
        [keys enumerateObjectsUsingBlock:^(NSString  *_Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            [mtbDic setObject:@"" forKey:key];
        }];
        
        [mtbDic setObject:@"" forKey:@"time"];
        _allDataArray = @[mtbDic];
        
        
    }
    
    //https://www.jianshu.com/p/9104d60bdec1
    //NSArray *newArray = [array valueForKeyPath:@"city"];
    NSMutableDictionary *params_dic = [NSMutableDictionary dictionary];
    NSMutableArray *timesArray = [NSMutableArray array];
    //233 有些温度值是32767的 ,需要显示 NA
    NSMutableArray *NanKeys = [NSMutableArray array];
    for (NSDictionary *dic in _allDataArray) {
        if (self.timeType == TimeType_Day) {//天数据
            NSTimeInterval interval = 0;
            if(dic[@"time"]){//电站
                interval = [dic[@"time"] integerValue]/1000.0;
            }
            if(dic[@"ts"]){//设备
                interval = [dic[@"ts"] integerValue]/1000.0;
            }
            
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
            NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
            [objDateformat setDateFormat:@"HH:mm"];
            //电芯电压和温度X轴展示秒数
            if(dic[@"timeFormat"]){
                [objDateformat setDateFormat:dic[@"timeFormat"]];
            }
            NSString *time = [objDateformat stringFromDate: date];
            
            //针对charts无数据时补充的假数据
            if([dic[@"time"] isKindOfClass:[NSString class]]){
                if([dic[@"time"]isEqualToString:@""]){
                    time = @"";
                }
            }
            
//            NSLog(@"time ------>%@",time);
            //全部获取
            for (NSString *key in dic.allKeys) {
                NSMutableArray *array = params_dic[key]?params_dic[key]:[NSMutableArray array];
                CGFloat num = [dic[key] doubleValue];
                //找出32767对应的key,并替换成30
                if ([dic[key] integerValue]==32767) {
                    [array addObject:@(50)];
                    if (![NanKeys containsObject:key]) {
                        [NanKeys addObject:key];
                    }
                }else{
                    [array addObject:@(num)];
                }
               
                [params_dic setObject:array forKey:key];
                
            }
            [timesArray addObject:time];
          
        }else{//年月
            NSTimeInterval interval = [dic[@"time"] integerValue]/1000.0;
            if(dic[@"ts"]){
                interval = [dic[@"ts"] integerValue]/1000.0;
            }
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
            NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
            [objDateformat setDateFormat:self.timeType == TimeType_Month?@"dd":@"MM"];
            NSString *time = [objDateformat stringFromDate: date];

            //针对charts无数据时补充的假数据
            if([dic[@"time"] isKindOfClass:[NSString class]]){
                if([dic[@"time"]isEqualToString:@""]){
                    time = @"";
                }
            }
            if(interval == 0){
                time = @"";
            }
            
            if (![timesArray containsObject:time]) {
                for (NSString *key in dic.allKeys) {
                    NSMutableArray *array = params_dic[key]?params_dic[key]:[NSMutableArray array];
                    CGFloat num = [dic[key] doubleValue];
                    [array addObject:@(num)];
                    [params_dic setObject:array forKey:key];
                }
                [timesArray addObject:time];
            }
            
            
        }
    }
    
    //设置曲线的y轴数据
    for (DeviceChartFieldModel *fielModel in self.selectArray){
        fielModel.hasNaNValue = NO;
        [NanKeys enumerateObjectsUsingBlock:^(NSString*  _Nonnull nan_key, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([fielModel.keyCode isEqualToString:nan_key]) {
                fielModel.hasNaNValue = YES;
            }
        }];
       
        fielModel.dataArray = params_dic[fielModel.keyCode]?params_dic[fielModel.keyCode]:@[];
        if (fielModel.dataArray.count>0) {
            //计算数据的最大值
            fielModel.value_max = [[fielModel.dataArray valueForKeyPath:@"@max.doubleValue"] doubleValue];
            fielModel.value_min = [[fielModel.dataArray valueForKeyPath:@"@min.doubleValue"] doubleValue];
        }
        
        //对于本地字段跟返回的字段不一致问题导致的崩溃
        if(fielModel.dataArray.count == 0){
            NSMutableArray *mtbArr = [NSMutableArray array];
            [timesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [mtbArr addObject:@(0)];
            }];
            fielModel.dataArray = mtbArr.copy;
        }
        
    }
    
    if (_allDataArray.count == 0) {
        //针对无数据时年月x轴显示问题
        NSMutableArray *xArray = [NSMutableArray array];
        NSMutableArray *yArray = [NSMutableArray array];
            if(self.timeType == TimeType_Month){
                for (int i = 1; i<=30; i++) {
                    NSString *month = [NSString stringWithFormat:@"%02d",i];
                    [timesArray addObject:month];
                }
            }
            if(self.timeType == TimeType_Year){
                for (int i = 1; i<=12; i++) {
                    NSString *year = [NSString stringWithFormat:@"%02d",i];
                    [timesArray addObject:year];
                }
            }
        
        self.yAxisArray = @[];
        //self.xTitlesArray = @[];
    }else{
        self.xTitlesArray = timesArray;
        //更新Y轴标签
        [self updateyAxisArray];
    }
    
    
}



#pragma mark -------- 更新Y轴 最大值 最小值
//更新Y轴标签组合
- (void)updateyAxisArray{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (DeviceChartFieldModel *fielModel in self.selectArray) {
        if (fielModel.isShowLine) {
            ChartYAxisModel *yAxisModel = dic[fielModel.unitName];
            if (yAxisModel) {
                yAxisModel.y_max = MAX(yAxisModel.y_max,fielModel.value_max);
                yAxisModel.y_min = MIN(yAxisModel.y_min,fielModel.value_min);
                
                //针对温度值出现 32767错误值 的处理
//                if (yAxisModel.y_max == 32767) {
//                    __block double max = 0;
//                    [fielModel.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                        if ([obj doubleValue]>max && ([obj doubleValue] != 32767)) {
//                            max = [obj doubleValue];
//                        }
//                    }];
//                    
//                    yAxisModel.y_max = max + 10;//错误值改为比最大值多10
//                }
            }else{
                ChartYAxisModel *model = [[ChartYAxisModel alloc] init];
                model.y_min = fielModel.value_min;
                model.y_max = fielModel.value_max;
                model.y_unit = fielModel.unitName?fielModel.unitName:@"";
                model.digit = 2;
                //针对温度值出现 32767错误值 的处理
//                if (model.y_max == 32767) {
//                    __block double max = 0;
//                    [fielModel.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                        NSLog(@"====>%@",[NSString stringWithFormat:@"%f",[obj doubleValue]]);
//                        if ([obj doubleValue]>max && ([obj doubleValue] != 32767)) {
//                            max = [obj doubleValue];
//                        }
//                    }];
//                    
//                    model.y_max = max + 10;//错误值改为比最大值多10
//                    
//                }
                [dic setObject:model forKey:fielModel.unitName?fielModel.unitName:@""];
                
                
            }
            
            
        }
    }
    //图表Y轴对应的最大值,最小值,单位 模型(这里)
    self.yAxisArray = [dic allValues];
    
    //处理一下最值
    [self.yAxisArray enumerateObjectsUsingBlock:^(ChartYAxisModel * _Nonnull yAxisModel, NSUInteger idx, BOOL * _Nonnull stop) {
        //如果两值相差0.几
        if (yAxisModel.y_max - yAxisModel.y_min < 1) {
            yAxisModel.y_max = yAxisModel.y_max+ (yAxisModel.y_max - yAxisModel.y_min);
            yAxisModel.y_min = yAxisModel.y_min;
            if (yAxisModel.y_max<0.01 && yAxisModel.y_max>0) {
                yAxisModel.y_max = 0.01;
                yAxisModel.digit = 3;
            }
        }
        //如果是百分比
        if ([yAxisModel.y_unit isEqualToString:@"%"]) {
            yAxisModel.y_max = 100;
            yAxisModel.y_min = 0.0;
        }
        //如果大小值相等
        if(yAxisModel.y_max == yAxisModel.y_min){
            yAxisModel.y_max = yAxisModel.y_min + 1;
        }
    }];
    
    for (DeviceChartFieldModel *fielModel in self.selectArray) {
        if (!fielModel.isShowLine) {
            continue;
        }
    
        for (ChartYAxisModel *yAxisModel in self.yAxisArray) {
            //有时点击不显示高亮图标,所以最大值加一点点
            if ([fielModel.unitName isEqualToString:yAxisModel.y_unit]) {
                fielModel.y_max = yAxisModel.y_max+0.0001;
                fielModel.y_min = yAxisModel.y_min;
            }
        }
    }
}


//为了让图表显示,造点假数据
-(void)creatDefaultChartDataWithChartModel
{
    NSMutableArray *keys = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in self.selectArray) {
        [keys addObject:fileld.keyName];
    }
    
    NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
    [keys enumerateObjectsUsingBlock:^(NSString  *_Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        [mtbDic setObject:@"" forKey:key];
    }];
    [mtbDic setObject:@"" forKey:@"time"];
    self.allDataArray = @[mtbDic];
}

- (NSInteger)y1_max{
    return 100;
}

- (NSInteger)y1_min{
    return  0;
}

- (NSInteger)y2_max{
    return 50;
}

- (NSInteger)y2_min{
    return 30;
}

//曲线全屏时复制一份
-(DevChartModel*)modelCopy
{
    DevChartModel *model = [[DevChartModel alloc] init];
    model.maxSelectCount = self.maxSelectCount;
    model.y2_unit = self.y2_unit;
    model.y2_max = self.y2_max;
    model.y2_min = self.y2_min;
    model.y1_unit = self.y1_unit;
    model.y1_max = self.y1_max;
    model.y1_min = self.y1_min;
    model.isAllowScale = YES;
    model.yAxisArray = [self.yAxisArray mutableCopy];
    model.xTitlesArray = [self.xTitlesArray mutableCopy];
    model.mYDataArray = [self.mYDataArray mutableCopy];
    model.allDataArray = [self.allDataArray mutableCopy];
    model.selectArray = [self.selectArray mutableCopy];
    model.yearParams = [self.yearParams mutableCopy];
    model.monthParams = [self.monthParams mutableCopy];
    model.dayParams = [self.dayParams mutableCopy];
    model.params = [self.params mutableCopy];
    model.curTime = self.curTime;
    model.timeType = self.timeType;
    model.colorArr = self.colorArr.copy;
    return model;
}


///测试数据
-(NSArray*)getTestData
{
    NSMutableArray *mtbArr = [NSMutableArray array];
   
    for (NSDictionary *dic in self.allDataArray) {
        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
        for (NSString *key in dic.allKeys) {
            if ([key isEqualToString:@"ts"]) {
                [mtbDic setObject:dic[key] forKey:key];
                continue;
            }
            NSInteger integ = arc4random_uniform(20);
            NSInteger dig = arc4random_uniform(100);
            NSString *value = [NSString stringWithFormat:@"%ld.%ld",integ,dig];
            [mtbDic setObject:value forKey:key];
        }
        [mtbArr addObject:mtbDic];
    }
    return mtbArr.copy;
}
@end
